#include<iostream>
using namespace std;
#include<vector>
class Solution {
public:
    int semiOrderedPermutation(vector<int>& nums) {
        int be = -1, n = nums.size(), la = n;
        for (int i = 0; i < n; ++i) {
            if (nums[i] == 1 && be == -1)
                be = i;
            if (nums[n - i - 1] == n && la == n)
                la = n - i - 1;
            if (be != -1 && la != n)
                break;
        }
        return be < la ? be + n - la - 1 : be + n - la - 2;
    }
};